<!-- 招标文件 -->
<template>
    <div class="app-container">
        <el-button type="primary" size="mini" v-if="this.$route.query.status!=7" @click="addFile">
            新建
        </el-button>

        <el-table v-loading="tableLoading" :data="tableData" stripe style="width: 100%">
            <el-table-column type="index" label="序号" width="50" align="center">
            </el-table-column>
            <el-table-column prop="bDocuId" v-if="false" label="文件id" align="center">
            </el-table-column>
            <el-table-column prop="name" label="文件名" align="center">
            </el-table-column>
            <el-table-column prop="size" label="文件大小" align="center">
            </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" align="center">
            </el-table-column>
            <el-table-column prop="address" label="操作" align="center">
                <template slot-scope="scope">
                    <el-button @click="previewNoticeRow(scope.row)" type="text" size="small">
                        预览
                    </el-button>
                    <el-button @click="deleteRow(scope.row)" type="text" size="small">
                        删除
                    </el-button>
                    <el-button @click="downloadMethod(scope.row)" type="text" size="small">
                        下载
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog title="文件预览" :visible.sync="previewOpen" width="50%">
            <vue-office-docx v-if="fileUrl.endsWith('.docx')" :src="fileUrl" />
            <vue-office-excel v-if="fileUrl.endsWith('.xlsx')" :src="fileUrl" />
            <vue-office-pdf v-if="fileUrl.endsWith('.pdf')" :src="fileUrl" />
            <div v-if="fileUrl.endsWith('.jpg') || fileUrl.endsWith('.png')"
                style="display: flex; justify-content: center; align-items: center;">
                <img style="width: 30%" :src="fileUrl" alt="图片加载失败" />
            </div>
        </el-dialog>

        <el-dialog title="添加附件" :visible.sync="insertOpen" width="50%">
            <el-form ref="form" :model="form" label-width="100px">
                <el-form-item label="文件标题" prop="name">
                    <el-input v-model="form.name" placeholder="请输入文件标题" />
                </el-form-item>
                <el-form-item label="附件">
                    <el-upload class="upload-demo" action="#" :limit="1" :http-request="uploadDeviceFile" :drag="true"
                        :before-upload="uploadFileFun" :file-list="form.fileList" :on-remove="handleRemoveFile">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip fontSize12 colorRed" slot="tip">
                            上传文件格式为word或pdf或png或者txt，文件大小在10M以内</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getFileListByINumber, addTenderFile, uplodaBudgetFile, deleteTenderFile } from '@/api/system/purchase'
// 引入相关样式
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'
// 引入 VueOffice 组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from
    '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'

export default {
    components: {
        VueOfficeDocx,
        VueOfficeExcel,
        VueOfficePdf
    },
    data() {
        return {
            form: {
                fileList: [],
                name: '',
            },
            previewOpen: false,
            tableData: [],
            fileUrl: '',
            insertOpen: false,
            iNumber: '',
            loading: true,
            tableLoading:true,
        }
    },
    methods: {
        previewNoticeRow(row) {            
            this.fileUrl = row.url;
            this.previewOpen = true;
        },
        deleteRow(row) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteTenderFile(row.bDocuId).then(res => {
                    if (res.data > 0) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.tableData = this.tableData.filter(item => item.bDocuId != row.bDocuId);
                    }
                })
            }).catch((err) => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        async downloadMethod(fileInfoL) {
            try {
                // 获取响应
                let response = await fetch(fileInfoL.url);

                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('网络响应失败');
                }

                // 内容转变成blob地址
                let blob = await response.blob();

                // 创建隐藏的可下载链接
                let objectUrl = window.URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.style.display = "none";
                a.href = objectUrl;
                a.download = fileInfoL.name;

                // 触发点击
                document.body.appendChild(a);
                a.click();

                // 移除
                URL.revokeObjectURL(a.href);
                document.body.removeChild(a);
            } catch (error) {
                console.error('下载文件时出错:', error);
            }
        },
        addFile() {
            this.insertOpen = true;
        },
        getFileList(iNumber) {
            getFileListByINumber(iNumber).then(res => {
                this.tableLoading=false;
                this.tableData = res.map(item => {
                    // 使用 split 方法将字符串按逗号分割，并取第一个元素
                    let nameParts = item.name.split('.');
                    // 去除前后的空格
                    let trimmedName = nameParts[0].trim();
                    let size = (item.size / 1024).toFixed(2) + " KB";
                    // 返回新的对象，只包含需要的属性
                    return { name: trimmedName, size: size, uploadTime: item.uploadTime, url: item.url, bDocuId: item.bDocuId };
                });
            })
        },
        uploadDeviceFile(file) {
            // 创建formdata实例
            let formData = new window.FormData();
            // 将获取的文件通过append方法加入实例中
            formData.append("file", file.file);
            //发送axios请求
            uplodaBudgetFile(formData)
                .then(res => {
                    // 拿到后端响应的文件名称反显到列表的form
                    const fileInfo = {
                        name: res.data.name,
                        url: res.data.url,
                        size: res.data.size,
                        uid: file.file.uid,
                    };
                    console.log(fileInfo);

                    this.form.fileList.push(fileInfo); // 直接添加文件名字符串        
                })
                .catch(err => {
                    console.error('上传文件失败:', err);
                });
        },
        //文件上传前的校验
        uploadFileFun(file) {
            var test = /(doc|docx|pdf|txt|png)$/.test(file.name.split('.').pop().toLowerCase());
            if (!test) {
                this.$message.error("请上传正确的文档格式!");
                return false;
            }
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!isLt2M) {
                this.$message.error("上传文件大小不能超过 10MB!");
                return false;
            }
        },
        //删除文件
        handleRemoveFile(file) {
            removeFile(file.name).then(res => {
                if (res.data == 1) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                }
                const index = this.form.fileList.findIndex(f => f.name === file.name);
                this.form.fileList.splice(index, 1); // 从 fileList 中移除一个元素，从 index 位置开始
            })
        },
        submitForm() {
            const form = {
                file: this.form.fileList,
                name: this.form.name,
                iNumber: this.iNumber
            }
            addTenderFile(form).then(res => {
                if (res.data > 0) {
                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    });
                }
                this.form = {
                    fileList: [],
                    name: '',
                }
                this.getFileList(this.iNumber);
                this.insertOpen = false;
            }).catch(err => {
                this.$message({
                    message: '添加失败',
                    type: 'error'
                });
            })
        },
        cancel() {
            this.open = false;
        },
    },
    mounted() {
        const query = this.$route.query.iNumber;
        this.iNumber = query;
        this.getFileList(query);
        console.log(this.$route.query,"这是测试路由中的参数");
    },
}
</script>
<style scoped></style>